package com.codeyang.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeyang.constant.IndexImgConstant;
import com.codeyang.domain.IndexImg;
import com.codeyang.domain.Prod;
import com.codeyang.feign.IndexImgProdFeign;
import com.codeyang.mapper.IndexImgMapper;
import com.codeyang.service.IndexImgService;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

/**
 * 描述: TO-删除标志-DO
 *
 * @author CodeYang_Site
 * @version 2021/5/26 13:53
 */
@CacheConfig(cacheNames = "com.codeyang.service.impl.IndexImgServiceImpl")
@Slf4j
@Service
public class IndexImgServiceImpl extends ServiceImpl<IndexImgMapper, IndexImg> implements IndexImgService {


    @Autowired
    private IndexImgMapper indexImgMapper;


    @Autowired
    private IndexImgProdFeign indexImgProdFeign;


    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Value("${resources.url}")
    private String serverHost;


    /**
     * 新增轮播图
     * 操作DB要干日志
     *
     * @param indexImg
     * @return
     */
    @CacheEvict(key = IndexImgConstant.INDEX_IMG_PREFIX)
    @Override
    public boolean save(IndexImg indexImg) {
        log.info("新增轮播图,信息{}", JSON.toJSONString(indexImg));
        //设置一些 缺省的默认信息
        indexImg.setUploadTime(new Date());
        indexImg.setShopId(1L);
        //先把
        return super.baseMapper.insert(indexImg) > 0;
    }

    /**
     * 根据轮播图id 拿到轮播对象信息
     * step:
     * 1.这里根据轮播图id 拿到轮播图对应的信息,一般要拿到轮播图对应的商品id
     * 2.涉及到远程调用跨服务了 需要使用 feign
     * 1.查询DB
     * 2.看有没有商品 可能是主图轮播是没有轮播的
     * 3.关联了商品 需要远程调用的商品  就需要得到 商品的name 和 pic 图片
     * 4.组装返回
     *
     * @param indexImgId
     * @return
     */
    @Override
    public IndexImg findIndexImgById(Long indexImgId) {
        //1.
        IndexImg indexImg = indexImgMapper.selectById(indexImgId);
        if (ObjectUtils.isEmpty(indexImg)) {
            return null;
        }
        //2. 得到关联的商品id
        Long prodId = indexImg.getRelation();
        if (ObjectUtils.isEmpty(prodId)) {
            //为null 没关联
            return indexImg;
        }
        //有关联
        //3.远程调用 -调用结束后一定要判空
        Prod prod = indexImgProdFeign.getProdInfoById(prodId);
        if (!ObjectUtils.isEmpty(prod)) {
            indexImg.setPic(prod.getPic());
            indexImg.setProdName(prod.getProdName());
        }
        return indexImg;
    }

    /**
     * 修改轮播图
     * step:
     * 1.先查出老的 img地址
     * 1.修改DB img_url 值
     * 2.判断修改 ->删除原来的 服务器图片 fstdfs
     *
     * @param entity
     * @return
     */
    @CacheEvict(key = IndexImgConstant.INDEX_IMG_PREFIX)
    @Override
    public boolean updateById(IndexImg indexImg) {
        log.info("修改轮播图{}", JSON.toJSONString(indexImg));
        indexImg.setUploadTime(new Date());

        //1.
        IndexImg oldIndexImg = indexImgMapper.selectById(indexImg.getImgId());

        //2.
        int count = indexImgMapper.updateById(indexImg);
        //3.
        String imgUrl = oldIndexImg.getImgUrl();
        // 拿到修改前的图片 从fastdfs删掉
        try {
            fastFileStorageClient.deleteFile(imgUrl);
        } catch (Exception e) {
            log.error("fastDfs删除文件错误:{}", e.getMessage());
        }

        return count > 0;
    }

    /**
     * 查询前台轮播图
     *
     * @return
     */
    @Cacheable(key = IndexImgConstant.INDEX_IMG_PREFIX)
    @Override
    public List<IndexImg> loadFrontCarousel() {
        //定制SQL查询字段 组合SQL
        //select img_url,relation from index_img where status = 1  order by seq desc limit 5
        List<IndexImg> indexImgs = indexImgMapper.selectList(
                new LambdaQueryWrapper<IndexImg>()
                        .eq(IndexImg::getStatus, 1)
                        .orderByDesc(IndexImg::getSeq)
                        .select(IndexImg::getImgUrl, IndexImg::getRelation)
                        .last(" limit 5")
                //  只取欠条
        );

        return indexImgs;
    }
}
